import FramePoint from '@/FramePoint';
import ObjectPool from '@/ObjectPool';
import { Frame } from '@/frame';
import UIChooseHeroModel from '../Model/UIChooseHeroModel';
import ForceUtil from '@/ForceUtil';
import BaseUtil from '@/BaseUtil';
import ColorStr from '@/ColorStr';
import SyncUtil from '@/SyncUtil';
import FrameTipUtil from '../common/FrameTipUtil';
import { type data_type as ChooseHeroConfigModel } from 'xlsx/common_heros';

function formatDesc(config: ChooseHeroConfigModel) {
    return `${ColorStr.yellow}英雄成长：|r|n|n体质：${config.STR} + ${config.STRplus}|n力量：${config.AGI} + ${config.AGIplus}|n敏捷：${config.CusAGI} + ${config.CusAGIplus}|n智力：${config.CusINT} + ${config.CusINTplus}|n精神：${config.INT} + ${config.INTplus}`;
}

export default class UIChooseHeroView {
    static instance: UIChooseHeroView;
    framePool: ObjectPool<Frame[]> = new ObjectPool<Frame[]>(() => {
        let f = Frame.createFrame().setSize(0.2, 0.3);
        let bg = new Frame('BACKDROP', null, null, '_sl_border_backdrop', 0);
        bg.setParent(f.current).setSize(0.2, 0.3).setPoint2Center(f.current);
        let head = Frame.createBackDrop().setParent(f.current).setSize(0.04, 0.04).setPoint(FramePoint.topLeft, f.current, FramePoint.topLeft, 0.02, -0.02);
        let name = Frame.createTEXT().setSize(0.1, 0.01).setParent(head.current).setPoint(FramePoint.top, head.current, FramePoint.bottom, 0, -0.01).setFont(0.012, 'fonts\\fonts.ttf');
        name.setTextAlignment(TEXTALIGN_CENTER);
        let desc = Frame.createTEXT().setSize(0.115, 0.1).setParent(f.current).setPoint(FramePoint.topRight, f.current, FramePoint.topRight, -0.01, -0.02).setFont(0.012, 'fonts\\fonts.ttf');
        let talent_drop = Frame.createBackDrop();
        talent_drop.setParent(f.current).setSize(0.04, 0.04).setPoint(FRAMEPOINT_TOPLEFT, f.current, FRAMEPOINT_TOPLEFT, 0.02, -0.12).setFont(0.012, 'fonts\\fonts.ttf');
        let t_title = Frame.createTEXT();
        t_title.setParent(talent_drop.current).setPoint(FRAMEPOINT_TOP, talent_drop.current, FRAMEPOINT_BOTTOM, 0, -0.005).setFont(0.012, 'fonts\\fonts.ttf');
        let talent_desc = Frame.createTEXT().setSize(0.115, 0.13).setParent(f.current).setPoint(FramePoint.topRight, f.current, FramePoint.topRight, -0.01, -0.12).setFont(0.012, 'fonts\\fonts.ttf');
        let button = Frame.createGLUEBUTTON();
        button.setParent(f.current).setSize(0.04, 0.02).setPoint(FRAMEPOINT_BOTTOM, f.current, FRAMEPOINT_BOTTOM, 0, 0.01);
        button.addBackgroundImage('assets\\common\\but_select.blp');
        button.setOnClick(this.chooseButtonClickHandler.bind(this));
        return [f, head, name, desc, talent_drop, t_title, talent_desc, button];
    });
    refreshRemainText: Frame;
    refreshButton: Frame;
    model: UIChooseHeroModel;
    roots: Frame[];
    // 以按钮为key，存储对应的英雄配置
    buttonMapConfig: { [key: number]: ChooseHeroConfigModel } = {};
    constructor() {
        UIChooseHeroView.instance = this;
        this.model = new UIChooseHeroModel();
        // 订阅难度选择完毕事件，当玩家1选好难度后绘制ui，供玩家进行英雄选择
        se.on('GAME_HARD_SELECTED', this.start.bind(this));

        // 订阅选择英雄的数据更新事件
        se.on('choose_hero_data_update', (p: player) => {
            this.refreshUI(p);
        });
    }

    // 选择对应英雄按钮的点击事件
    chooseButtonClickHandler() {
        let h = DzGetTriggerUIEventFrame();
        let config = this.buttonMapConfig[h];
        let { TalentId, CusAGI, CusINT, id } = config;
        SyncUtil.syncObjData('choose_hero_button_click', { TalentId, id, CusAGI, CusINT });
        // 隐藏UI
        this.refreshButton.visible = false;
        this.refreshRemainText.visible = false;
        for (let f of this.roots) {
            f.visible = false;
        }
    }
    start() {
        // 把玩家的待选英雄数据初始化
        let count = ForceUtil.getUserCount();
        for (let i = 0; i < count; i++) {
            this.model.DB[i].filterHeroList = this.model.randomHeros(i);
        }
        BaseUtil.runLater(1, () => {
            let p = GetLocalPlayer();
            // 刷新按钮与剩余刷新数据文本
            let root = DzGetGameUI();
            let refreshBut = (this.refreshButton = Frame.createGLUEBUTTON());
            refreshBut.setSize(0.04, 0.015).setParent(root).setPoint(FRAMEPOINT_BOTTOM, root, FRAMEPOINT_BOTTOM, 0, 0.15);
            refreshBut.addBackgroundImage('assets\\common\\but_refresh.blp');
            refreshBut.setOnClick(this.refreshClickHandler.bind(this));
            let t = (this.refreshRemainText = Frame.createTEXT());
            t.setParent(refreshBut.current)
                .setSize(0.13, 0.015)
                .setPoint(FRAMEPOINT_BOTTOM, refreshBut.current, FRAMEPOINT_TOP, 0, 0.005)
                // .setText('剩余刷新次数：' + this.model.getPlayerRemainRefresh(p))
                .setFont(0.01113, 'fonts\\fonts.ttf')
                .setTextAlignment(TEXTALIGN_CENTER);
            // 绘制ui
            this.refreshUI(p);
        });
    }
    // 根据数据刷新ui
    refreshUI(p?: player) {
        if (p != GetLocalPlayer()) return;
        // let _this = UIChooseHeroView.instance;
        let pool = this.framePool;
        this.roots = [];
        pool.setAllIdleStatus(true);
        let list = this.model.getPlayerFilterHeros(p);
        for (let i = 0; i < list.length; i++) {
            let config = list[i];
            let [f, head, name, desc, tl_d, title, talent_desc, button] = pool.borrowObject();
            f.setAbsPoint(FramePoint.topLeft, 0.05 + 0.25 * i, 0.5);
            head.setTexture(config.Art);
            name.setText(`${ColorStr.orange}${config.Name}`);
            desc.setText(formatDesc(config));
            let talent = TalentManager.getTalentById(config.TalentId);
            if (talent == null) continue;
            tl_d.setTexture(talent.art);
            title.setText(`${ColorStr.red}${talent.abilityName}`);
            talent_desc.setText(`${ColorStr.yellow}天赋技能：|r|n|n` + talent.desc);
            this.buttonMapConfig[button.current] = config;
            this.roots.push(f);
        }

        this.refreshRemainText.setText('剩余刷新次数：' + this.model.getPlayerRemainRefresh(p));

        pool.forDirtyObjects((f) => (f[0].visible = false));
    }
    // 刷新按钮点击事件
    refreshClickHandler() {
        let p = DzGetTriggerUIEventPlayer();
        let remain = this.model.getPlayerRemainRefresh(p);
        if (remain <= 0) {
            FrameTipUtil.showFailText('刷新次数已经用完了，请选择英雄开始游戏');
            return;
        }
        SyncUtil.syncData('hero_refresh_button_click');
    }
}
